<template>
    <view>
        <view class="main">
            <!-- 订单详情 -->
            <view class="block1">
                <view class="block-title">订单详情</view>
                <view class="block1-content">
                    <view class="detailList">
                        <view class="detailList-item" v-for="(item, index) in detailInfo.commodityList" :key="item.commodityId">
                            <view class="detailList-item-left">
                                <image class="commodityImg" :src="item.imageUrl"></image>
                                <view class="detailList-item-info">
                                    <view class="detailList-item-name">{{ item.commodityName }}</view>
                                    <view class="detailList-item-count">一人份/{{ item.specs }}{{ item.unitName }}</view>
                                    <view class="detailList-item-count">X{{ item.count }}</view>
                                </view>
                            </view>

                            <view class="detailList-item-price">
                                <text class="dw">¥</text>
                                {{ filters.toFix(item.subtotalPrice) }}
                            </view>
                        </view>
                    </view>
                    <view class="detail-price-total">
                        订单合计：
                        <text class="dw">¥</text>
                        <text class="total-price">{{ totalMoney }}</text>
                    </view>
                </view>
            </view>
            <view class="gray-block"></view>
            <!-- 送餐信息 -->
            <view class="block2">
                <view class="block-title">送餐信息</view>
                <view class="block2-content">
                    <view class="detail-address">送餐地址：{{ detailInfo.address }}</view>
                    <view class="detail-info">取餐人：{{ name }}</view>
                    <view class="detail-info">下单时间：{{ detailInfo.createTime }}</view>
                    <view class="detail-info">
                        联系商家：
                        <image class="phoneImg" mode="widthFix" :data-phone="detailInfo.storeManagePhoneNumber" @tap.stop.prevent="call" src="/static/assets/img/phone.png"></image>
                    </view>
                </view>
            </view>
            <view class="gray-block"></view>
            <!-- 取消原因 -->
            <view class="block3">
                <block v-if="indexType == 0 || indexType == 1 || indexType == 2">
                    <view class="block-title">取消原因</view>
                    <view class="block3-content">
                        <van-radio-group v-model="radio" @change="onChange">
                            <van-cell-group>
                                <van-cell
                                    :title="item.value"
                                    clickable
                                    :data-name="item.code"
                                    @click="onClick($event, { name: item.code })"
                                    v-for="(item, index) in resonList"
                                    :key="item.code"
                                >
                                    <van-radio slot="right-icon" checked-color="#FFA000" :name="item.code" />
                                </van-cell>
                            </van-cell-group>
                        </van-radio-group>
                    </view>
                </block>
                <block v-if="indexType == 3">
                    <view class="block-title" v-if="detailInfo.cancelPersonType == 1">商家取消备注</view>
                    <view class="block-title" v-else>取消原因</view>
                    <view class="block3-content">
                        <view class="cancel-reason" v-if="detailInfo.cancelPersonType == 1">{{ detailInfo.remark || '无' }}</view>
                        <view class="cancel-reason" v-else>{{ detailInfo.cancelReason || detailInfo.remark || '无' }}</view>
                    </view>
                </block>
            </view>
        </view>
        <view class="cancle-block" v-if="indexType == 0 || indexType == 1 || indexType == 2">
            <view class="cancle-btn" @tap="goCancel">取消订单</view>
        </view>

        <!-- <view class="container1" style="display: none;">
  <view class="appoint-list">
    <view class="appoint-item">
      <view class="appoint-item-part1">
        <view class="item-content" wx:if="{{appointList&&appointList.length>0}}">
          <view class="box">
            <view class="titleInfo">订单详情</view>
            <view class="item" wx:for="{{appointList}}" wx:key="id">
              <image src="{{item.imageUrl}}"></image>
              <view class="rightInfo">
                <text class="title info">{{item.commodityName}}</text>
                <view class="content info">一人份/{{item.specs}}{{item.unitName}}</view>
                <view class="price info">￥ {{item.subtotalPrice}} 元</view>
                <view class="num">×{{item.num}}</view>


              </view>
            </view>

            <view class="totalMoney"><span
                style="font-family: PingFangSC-Regular;font-size: 28rpx;color: #6D6D6D;">订单合计:</span>¥{{totalMoney}}
            </view>
          </view>
        </view>
        <view wx:else>
          <noData />
        </view>
      </view>
      <view class="appoint-item-part2">
        <text class="title">送餐信息</text>
        <view class="appoint-item-content">送餐地址：{{allData.address}}</view>
        <view class="appoint-item-content">取餐人：{{allData.name}}<image mode="widthFix"
            data-phone="{{allData.phoneNumber}}" catchtap="call" src="/assets/img/phone.png" class="buttonPhone">
          </image>
        </view>
        <view class="appoint-item-content">下单时间：{{allData.createTime}}</view>
      </view>
      <view class="appoint-item-part3">
        <text class="title">商家备注</text>
        <textarea class="textarea contentInput" model:value="{{content}}" placeholder-style="color:#999999;"
          placeholder="请输入备注信息" />
      </view>
    </view>
  </view>






  <view wx:if="{{allData.orderStatus!=1&&allData.orderStatus!=2&&allData.orderStatus!=3}}" class="bottom-bar">
    <view class="unbtn">
      <text class="unorder" bindtap='unOrder'>取消订单</text>
    </view>
    <view class="btn">
      <text bindtap='sureOrder'>确认接单</text>
    </view>
  </view>
</view> -->
    </view>
</template>
<script module="filters" lang="wxs" src="../../utils/filter.wxs"></script>
<script>
const app = getApp();

const { commodityQueryList, orderSave, orderDetail, orderCancelOrder, orderUpdateStatus, orderCancelReason } = require('utils/api');

export default {
    data() {
        return {
            userInfo: {},
            searchText: '',
            currSelect: {},

            // 统计商品数量和价格
            orderCount: {
                num: 0,
                money: 0
            },

            orderList: [],
            bottomFlag: false,

            // 提交的订单
            orders: true,

            items: [],
            resonList: [],
            radio: '',
            detailId: '',

            detailInfo: {
                commodityList: [],
                address: '',
                createTime: '',
                storeManagePhoneNumber: '',
                cancelPersonType: 0,
                remark: '',
                cancelReason: ''
            },

            //0 待处理 3 已取消
            indexType: 0,

            addressName: '',
            phoneNumber: '',
            name: '',
            appointList: '',
            totalMoney: '',
            allData: '',
            content: '',
            storeId: '',
            custPhone: ''
        };
    },
    onLoad: function (options) {
        if (options) {
            this.setData({
                detailId: options.id,
                indexType: options.activeIndex || 0
            });
        } else {
            this.setData({
                detailId: 26
            });
        }

        this.setData({
            addressName: uni.getStorageSync('addressName'),
            phoneNumber: uni.getStorageSync('phoneNumber'),
            name: uni.getStorageSync('name')
        });
        this.getReason();
        this.getDatailData();
    },
    methods: {
        //radio改变
        onChange(event) {
            this.setData({
                radio: event.detail
            });
        },

        //radio单项点击
        onClick(event, _dataset) {
            /* ---处理dataset begin--- */
            this.datasetHandle(event, _dataset);
            /* ---处理dataset end--- */
            const { name } = event.currentTarget.dataset;
            this.setData({
                radio: name
            });
        },

        // 点击对应菜单添加按钮
        del: function (event) {
            let that = this;
            let id = event.target.dataset.id;
            let index = event.target.dataset.index;
            let param = this.appointList[index];

            if (param.num > 0) {
                param.num--; // 每点一次减少1
            } else {
                param.num = 0; // 最低为0
            } // 改变添加按钮的状态

            this.appointList.splice(index, 1, param);
            that.setData({
                appointList: this.appointList
            });
            let money = 0;
            let num = 0; // 将已经确定总价格和数量求和

            this.appointList.forEach((item) => {
                money += item.price * item.num;
                num += item.num;
            });
            money = money.toFixed(2);
            let orderCount = {
                num,
                money
            };
            this.setData({
                orderCount
            });
        },

        unOrder() {
            var unOrderJson = {
                id: this.allData.id,
                remark: this.content
            };
            uni.$post(orderCancelOrder, unOrderJson)
                .then((res) => {
                    //请求成功
                    if (res.code == 0) {
                        uni.showModal({
                            title: '',
                            content: '取消订单成功',
                            showCancel: false,
                            confirmText: '我知道了',
                            confirmColor: '#FFA000',

                            success(res) {
                                uni.redirectTo({
                                    url: '/pages/businessOrderMeal1/businessOrderMeal1'
                                });
                            }
                        });
                    } else {
                        this.setData({
                            appointList: []
                        });
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                })
                .catch((err) => {
                    //请求失败
                });
        },

        sureOrder() {
            var sureOrderJson = {
                orderStatus: 1,
                remark: this.content,
                id: this.allData.id
            };
            uni.$post(orderUpdateStatus, sureOrderJson)
                .then((res) => {
                    //请求成功
                    if (res.code == 0) {
                        uni.redirectTo({
                            url: '/pages/businessOrderMeal1/businessOrderMeal1?orderStatus=1'
                        });
                    } else {
                        this.setData({
                            appointList: []
                        });
                        uni.showModal({
                            title: '',
                            content: res.msg,
                            showCancel: false,
                            confirmText: '我知道了',
                            confirmColor: '#FFA000',

                            success(res) {
                                uni.redirectTo({
                                    url: '/pages/businessOrderMeal1/businessOrderMeal1?orderStatus=1'
                                });
                            }
                        });
                    }
                })
                .catch((err) => {
                    //请求失败
                });
        },

        handleSearch() {
            var queryJson = {
                storeId: this.id
            };
            uni.$post(commodityQueryList, queryJson)
                .then((res) => {
                    //请求成功
                    if (res.code == 0) {
                        var appointList = res.data;
                        var length = appointList.length;
                        if (length > 0) {
                            for (var i = 0; i < length; i++) {
                                appointList[i].num = 0;
                            }

                            this.setData({
                                appointList: appointList
                            });
                        } else {
                            this.setData({
                                appointList: []
                            });
                            uni.showToast({
                                title: '抱歉，商品列表为空！',
                                icon: 'none'
                            });
                        }
                    } else {
                        this.setData({
                            appointList: []
                        });
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                })
                .catch((err) => {
                    //请求失败
                });
        },

        // 点击对应菜单添加按钮
        add: function (event) {
            let that = this;
            let id = event.target.dataset.id;
            let index = event.target.dataset.index;
            let param = this.appointList[index];
            let subOrders = []; // 购物单列表存储数据

            param.num++; // 每点一次增加1
            // 改变添加按钮的状态
            this.appointList.splice(index, 1, param);
            that.setData({
                appointList: this.appointList
            });
            let money = 0;
            let num = 0; // 将已经确定总价格和数量求和

            this.appointList.forEach((item) => {
                money += item.price * item.num;
                num += item.num;
            });
            money = money.toFixed(2);
            let orderCount = {
                num,
                money
            }; // 设置显示对应的总数和全部价钱

            this.setData({
                orderCount
            });
        },

        // 点击结账按钮
        pay: function () {
            let that = this;
            let str = '选中' + that.orderCount.num + '件商品，共' + that.orderCount.money + '元，是否要支付？';
            uni.showModal({
                title: '提示',
                content: str,
                success: function (res) {
                    var commodityList = [];

                    for (var i = 0; i < that.appointList.length; i++) {
                        commodityList.push({
                            commodityId: that.appointList[i].id,
                            count: that.appointList[i].num,
                            subtotalPrice: that.appointList[i].price * that.appointList[i].num
                        });
                    }

                    var payPar = {
                        phoneNumber: that.phoneNumber,
                        address: that.addressName,
                        custName: that.name,
                        totalPrice: that.orderCount.money,
                        storeId: that.storeId,
                        commodityList: commodityList // "commodityList":[
                        //     {"commodityId":5,"count":2,"subtotalPrice":"199.98"},
                        //     {"commodityId":6,"count":3,"subtotalPrice":"299.97"}
                        // ]
                    };
                    uni.$post(orderSave, payPar)
                        .then((res) => {
                            //请求成功
                            if (res.code == 0) {
                                uni.showModal({
                                    title: '',
                                    content: '感谢您的订餐，可在“我的订单”中查询订餐进展，请耐心等待',
                                    showCancel: false,
                                    confirmText: '我知道了',
                                    confirmColor: '#FFA000',

                                    success(res) {
                                        uni.redirectTo({
                                            url: '/pages/personOrderMeal1/personOrderMeal1'
                                        });
                                    }
                                });
                            } else {
                                uni.showToast({
                                    title: '抱歉，预定失败，请重试！',
                                    icon: 'none'
                                });
                            }
                        })
                        .catch((err) => {
                            //请求失败
                        });
                }
            });
        },

        getDatailData() {
            // var queryJson={
            //   id: this.data.storeId,
            //   personType:"1"
            // };
            var queryJson = {
                id: this.detailId,
                personType: 0
            };
            uni.$post(orderDetail, queryJson)
                .then((res) => {
                    //请求成功
                    if (res.code == 0) {
                        var appointList = res.data.commodityList;
                        var allData = res.data;
                        var length = appointList.length;
                        var content = allData.remark;
                        var totalMoney = 0;

                        if (length > 0) {
                            for (var i = 0; i < length; i++) {
                                totalMoney += parseInt(appointList[i].subtotalPrice);
                                appointList[i].num = appointList[i].count;
                            }

                            this.setData({
                                totalMoney: totalMoney,
                                appointList: appointList,
                                allData: allData,
                                content: content,
                                detailInfo: res.data
                            });
                        } else {
                            this.setData({
                                appointList: []
                            });
                            uni.showToast({
                                title: '抱歉，商品列表为空！',
                                icon: 'none'
                            });
                        }
                    } else {
                        this.setData({
                            appointList: []
                        });
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                })
                .catch((err) => {
                    //请求失败
                });
        },

        goPage(event) {
            if (event.currentTarget.dataset.url) {
                uni.navigateTo({
                    url: event.currentTarget.dataset.url
                });
            } else {
                uni.showModal({
                    title: '',
                    content: '该板块正在建设中',
                    showCancel: false,
                    confirmText: '我知道了',
                    confirmColor: '#FFA000',

                    success(res) {
                        if (res.confirm) {
                            // console.log('用户点击确定')
                        }
                    }
                });
            }
        },

        call(event) {
            if (event.currentTarget.dataset.phone) {
				if(uni.getStorageSync('weixin') == 3 || uni.getStorageSync('weixin') == 4){
					ZWJSBridge.phoneCall({
					  "corpId": event.currentTarget.dataset.phone
					}).then(res => {
					  console.log(res)
					}).catch(err => {
					  console.log(err) 
					})
				}else{
					uni.makePhoneCall({
						phoneNumber: event.currentTarget.dataset.phone
					}).catch((e) => {
						console.log(e);
					});
				}
            }
        },

        getLoadData(options) {
            //原onLoad 中内容
            // console.log(options)
            let storeId = options.id; // console.log(parseInt(id));

            let custPhone = options.custPhone; // console.log(parseInt(id));

            this.setData({
                // appointListDetail:this.data.appointList[parseInt(id)],
                storeId: storeId,
                appointList: uni.getStorageSync('orderPay').orderList,
                orderCount: uni.getStorageSync('orderPay').orderCount,
                userInfo: uni.getStorageSync('userDetail'),
                addressName: uni.getStorageSync('addressName'),
                phoneNumber: uni.getStorageSync('phoneNumber'),
                name: uni.getStorageSync('name'),
                custPhone: custPhone
            });
            let that = this; // 取出订单传过来的数据
            // that.setData({
            //   // items: [{"id":1,"title":"湖南辣椒小炒肉1","price":12,"active":true,"num":1},{"id":2,"title":"湖南辣椒小炒肉2","price":13,"active":true,"num":1},{"id":3,"title":"湖南辣椒小炒肉3","price":14,"active":true,"num":1}]
            // });

            this.getDatailData();
        },

        //获取取消订单原因列表
        getReason() {
            uni.$post(orderCancelReason).then((res) => {
                if (res.code == 0) {
                    if (res.data && res.data.length > 0) {
                        this.setData({
                            resonList: JSON.parse(res.data)
                        });
                    }
                } else {
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    });
                }
            });
        },

        goCancel() {
            uni.showModal({
                title: '',
                content: '请确认是否取消订单？',
                showCancel: true,
                cancelText: '取消',
                cancelColor: '#999',
                confirmText: '确认',
                confirmColor: '#FFA000',
                success: (res) => {
                    if (res.confirm) {
                        this.cancleOrder();
                    } else if (res.cancel) {
                    }
                }
            });
        },

        //取消订单
        cancleOrder() {
            let param = {
                id: this.detailId,
                cancelReasonType: this.radio,
                personType: 0 //取消人类型:0订餐人，1商户管理员
            };
            uni.$post(orderCancelOrder, param).then((res) => {
                if (res.code == 0) {
                    uni.showToast({
                        title: res.data,
                        icon: 'none'
                    });
                    uni.navigateBack({
                        delta: 1
                    });
                } else {
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    });
                }
            });
        }
    }
};
</script>
<style>
@import './myOrderDetail.css';
</style>
